<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>手动旋转相机</title>
    <script src="https://cdn.bootcss.com/three.js/r83/three.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/1.9.0/jquery.min.js"></script>
    <style>
      html,body {
        padding:0;
        margin:0;
      }
    </style>
</head>
<body>
<div id="container"></div>

<script type="text/javascript">
    $(function(){
        var container;
        var camera,scene,renderer,light;
        var mesh;

        //这个mouseX和mouseY 记录的是鼠标相对于屏幕中心的位置，所以mouseX的范围是[-屏幕宽的一半，屏幕宽的一半]，mouseY的范围是[-屏幕高的一半，屏幕高的一半]
        var mouseX = 0,mouseY = 0;

        var windowHalfX = window.innerWidth/2;
        var windowHalfY = window.innerHeight/2;

        init();
        animate();

        function init(){
            scene = new THREE.Scene();

            container = document.getElementById('container');

            camera = new THREE.PerspectiveCamera(40,window.innerWidth/window.innerHeight,1,1000);
            camera.position.z = 180;
            camera.lookAt(scene.position);

            
            light = new THREE.DirectionalLight(0xffffff,1);
            light.position.set(0,0,10);
            scene.add(light);
            

            var cubeGeometry = new THREE.CubeGeometry(30,30,30); //建立几何体
            var cubeMaterial = new THREE.MeshLambertMaterial({color:0xff0000 }); //网格基本材质

            mesh = new THREE.Mesh(cubeGeometry,cubeMaterial);

            scene.add(mesh);

            renderer = new THREE.WebGLRenderer({antialias:true});
            renderer.setSize(window.innerWidth,window.innerHeight);
            renderer.setClearColor(0xFFFFFF, 1.0);
            container.appendChild(renderer.domElement);

            document.addEventListener('mousemove',onDocumentMouseMove,false);
            window.addEventListener( 'resize', onWindowResize, false );
        }

        function onWindowResize(){

            windowHalfX = window.innerWidth/2;
            windowHalfY = window.innerHeight/2;

            camera.aspect = window.innerWidth/window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize(window.innerWidth,window.innerHeight);

        }

        function onDocumentMouseMove(){

            //因为世界坐标系的原点在屏幕的中心，所以，将屏幕实际坐标减去屏幕宽高的一半，就将屏幕坐标的坐标原点移到世界坐标系的原点。
            mouseX = (event.clientX-windowHalfX);
            mouseY = (event.clientY-windowHalfY);

        }

        function animate(){

            requestAnimationFrame(animate);

            render();

        }

        function render(){

            //根据mouseX和mouseY改变相机的坐标
            camera.position.x += (mouseX - camera.position.x);
            camera.position.y += (mouseY - camera.position.y);

            camera.lookAt(scene.position);


            renderer.render( scene, camera );

        }

    });
</script>


</body>
</html>